import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import { useSize } from 'ahooks';
import { isDark } from '#/utils/utils.js';
import getOption from './getOption';
import { useThemeChange } from '@/hooks';
import _ from 'lodash';

/**
 *
 * @param {string} group 分组联动
 * @param {*} style 额外样式,如: { height: 200 }
 * @param {*} option 已缩减的配置，详见【getOption】
 * 全部已缩减项：
 diy = false, // 例：为true 时，则不适用缩减配置，直接使用传入配置
 grid, // obj，例：{ top: 0, left: 0, right: 0, bottom: 0 }
 xAxis = [], // 例: [{ formatter: () => {}  }]
 yAxis = [], // 例：[{ type: 'value', name: '单位: MW' }]
 dataset, // obj，例：{ source: [], dimensions: [] }
 legend, // obj，例：{}
 tooltip, // obj，例：{ formatter: () => {}, position: () => {} }
 series = [], // 系列，例：{ type, name, color, props }, 额外属性丢入props内
 timeline, // obj { title: '时间线', data: [], options: [] }
 dataZoomInside = false, // 内部滚动
 dataZoomSlider = false, // 外部滚动
 callBack = function， // chart渲染完成以后的回调函数
 */
export default ({ group, style = {}, option = null, getImg, callBack }) => {
  const chartIns = useRef();
  const chartRef = useRef(null);
  const chartSize = useSize(chartRef);
  // const { theme } = useThemeChange();

  useEffect(() => {
    // 创建图表
    chartIns.current =
      echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
    if (typeof group === 'string') {
      // 创建分组
      chartIns.current.group = group;
      echarts.connect(group);
    }
  }, [chartRef]);

  useEffect(() => {
    // 响应式
    if (!chartSize?.width) return;
    chartIns.current?.resize();
  }, [chartSize]);

  useEffect(() => {
    if (!option) return chartIns.current?.setOption({}, true); // fix
    const chartOption = getOption(option);
    if (!chartOption) return;
    chartIns.current?.setOption(_.cloneDeep(chartOption), true); // 更新视图
    if (typeof getImg === 'function') {
      const Base64Image = chartIns.current?.getDataURL({
        type: 'png',
        pixelRatio: 1,
        backgroundColor: isDark() ? '#222629' : '',
      });
      getImg(Base64Image);
    }
    typeof callBack === 'function' && callBack(chartIns.current);
  }, [JSON.stringify(option)]);

  // useEffect(() => {
  //   const chartOption = { ...getOption(option) };
  //   if (!chartOption) return;
  //   console.log(chartOption);
  //   chartIns.current?.setOption(chartOption, true); // 更新视图
  // }, [theme]);

  return (
    <div
      ref={chartRef}
      style={{
        width: '100%',
        height: '100%',
        ...style,
      }}
    />
  );
};
